package com.alibaba.nacos.core.remote;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ClientConnectionEventListenerRegistry implements ApplicationListener<ContextRefreshedEvent> {

    private final List<ClientConnectionEventListener> clientConnectionEventListeners = new ArrayList<>();

    public void notifyClientConnected(Connection connection) {
        for (ClientConnectionEventListener listener : clientConnectionEventListeners) {
            try {
                listener.clientConnected(connection);
            } catch (Throwable throwable) {
                log.error("[notifyClientConnected] failed for listener: {}", listener.getName(), throwable);
            }
        }
    }

    public void notifyClientDisConnected(Connection connection) {
        for (ClientConnectionEventListener listener : clientConnectionEventListeners) {
            try {
                listener.clientDisConnected(connection);
            } catch (Throwable throwable) {
                log.error("[notifyClientConnected] failed for listener: {}", listener.getName(), throwable);
            }
        }
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        event.getApplicationContext().getBeansOfType(ClientConnectionEventListener.class).values().forEach(listener -> {
            clientConnectionEventListeners.add(listener);
        });
    }
}
